package com.xls.box2023.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzz.bottomencapsulation.holder.MvpRVViewHolder;
import com.lzz.bottomencapsulation.utils.AppUtils;
import com.lzz.bottomencapsulation.utils.LUtils;
import com.lzz.bottomencapsulation.utils.TUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xls.box2023.Consts.StateConsts;
import com.xls.box2023.R;
import com.xls.box2023.customcontrol.RoundedImageView;
import com.xls.box2023.entity.YouXiEntity;
import com.xls.box2023.manager.APKDownLoadEntity;
import com.xls.box2023.manager.APKDownLoadManager;
import com.xls.resource.dialog.utils.download.PackageUtil;

import java.io.File;
import java.util.List;


/**
 * 首页游戏列表----item
 */
public class YouXiItemViewHolder extends MvpRVViewHolder<YouXiEntity> {
    private RoundedImageView youxi_icon;
    private TextView youxi_state;
    private TextView youxi_name;
    private TextView youxi_org;
    private TextView youxi_jifen;
    private TextView youxi_content;
    Activity activity;
    private String text_down="下载",text_down_loading="下载中～",text_anzhuang="安装",text_generateing="获取中～";
    public YouXiItemViewHolder(Activity context, ViewGroup p) {
        super(R.layout.item_youxi, context, p);
        this.activity=context;
//        if (!EventBus.getDefault().isRegistered(this)){ EventBus.getDefault().register(this); }//注册eventbus
    }

    @Override
    public void initView() {
        youxi_icon = itemView.findViewById(R.id.youxi_icon);
        youxi_state = itemView.findViewById(R.id.youxi_state);
        youxi_name = itemView.findViewById(R.id.youxi_name);
        youxi_org = itemView.findViewById(R.id.youxi_org);
        youxi_jifen = itemView.findViewById(R.id.youxi_jifen);
        youxi_content=itemView.findViewById(R.id.youxi_content);

//        游戏图标
        if (!TextUtils.isEmpty(viewData.getPicture())){
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .cacheInMemory(false)// 设置下载的图片是否缓存在内存中
                    .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
                    .build();
            ImageLoader.getInstance().displayImage(viewData.getPicture(),youxi_icon, options);
        }

        if (!TextUtils.isEmpty(viewData.getAppName())){
            youxi_name.setText(viewData.getAppName());
        }else {
            youxi_name.setText(" ");
        }

        if (!TextUtils.isEmpty(viewData.getTenantName())){
            youxi_org.setText(viewData.getTenantName());
        }else {
            youxi_org.setText(" ");
        }

        if (!TextUtils.isEmpty(viewData.getContent())){
            youxi_content.setText(viewData.getContent());
        }else {
            youxi_content.setText(" ");
        }

        if (viewData.getDownStatus()== StateConsts.DowmStatus.ok){
//            已下载过的页面展示
            youxi_jifen.setVisibility(View.INVISIBLE);
        }else {
            if (viewData.getDownCoins()>0){
                //            未下载过的页面展示
                youxi_jifen.setVisibility(View.VISIBLE);
                youxi_jifen.setText("下载需要\n"+viewData.getDownCoins()+" 金币");
            }
        }
        youxi_state.setOnClickListener(this);
        setSateTextShow();
    }

    private void setSateTextShow() {
        String state= APKDownLoadManager.getInstance().getAPKState(viewData.getAppId());
        if (TextUtils.equals(state,APKDownLoadManager.State.generateing)){
            youxi_state.setText(text_generateing);
            youxi_state.setBackgroundColor(Color.parseColor("#4BB3FF"));
        } else if (TextUtils.equals(state,APKDownLoadManager.State.downloading)){
            youxi_state.setText(text_down_loading);
            youxi_state.setBackgroundColor(Color.parseColor("#4BB3FF"));
        }else if (TextUtils.equals(state,APKDownLoadManager.State.ok)){
            youxi_state.setText(text_anzhuang);
            youxi_state.setBackgroundColor(Color.parseColor("#F6B756"));
        }else if (TextUtils.equals(state,APKDownLoadManager.State.stop)){
            youxi_state.setText(text_down);
            youxi_state.setBackgroundColor(Color.parseColor("#4BB3FF"));
        }else {
            youxi_state.setText(text_down);
            youxi_state.setBackgroundColor(Color.parseColor("#4BB3FF"));
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.youxi_state) {
//            检测是否已经安装了软件
            openAPP();
        }
    }

    /**
     * 打开app
     */
    private void openAPP() {
        XXPermissions.with(activity)
                // 申请单个权限
                .permission(Permission.READ_PHONE_STATE)
                .permission(Permission.READ_MEDIA_IMAGES)
                .permission(Permission.READ_PHONE_NUMBERS)
                .permission(Permission.READ_MEDIA_AUDIO)
                .permission(Permission.READ_MEDIA_VIDEO)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            Intent intent=activity.getPackageManager().getLaunchIntentForPackage(viewData.getPackageName());
                            if (intent!=null){
                                activity.startActivity(intent);
                                return;
                            }
                        }
                        onClickState();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        onClickState();
                    }
                });
    }

    public void  onClickState(){
        String stateText=youxi_state.getText().toString().trim();
        if (TextUtils.equals(text_down,stateText)){
            APKDownLoadManager.getInstance().start(activity,viewData);
        }else if (TextUtils.equals(text_anzhuang,stateText)){
            APKDownLoadEntity apkDownLoadEntity=APKDownLoadManager.getInstance().getAPKDownLoad(viewData.getAppId());
            File file=new File(apkDownLoadEntity.getFilePath());
            if (file.exists()&&file.length()==apkDownLoadEntity.getFileSize()&& PackageUtil.computeMD5(new File(apkDownLoadEntity.getFilePath())).toUpperCase().equals(apkDownLoadEntity.getFileMd5().toUpperCase())){
                //                下载完成  安装
                AppUtils.anZhuangAPk(context,apkDownLoadEntity.getFilePath());
            }else {
                TUtils.showShort(context,"安装包失效，请重新下载");
                youxi_state.setText(text_down);
                youxi_state.setBackgroundColor(Color.parseColor("#4BB3FF"));
            }
        }else if (stateText.contains(text_down_loading)){
            TUtils.showShort(context,"正在下载中，请稍后～");
        }else if (stateText.contains(text_generateing)){
            TUtils.showShort(context,"正在获取中，请稍后～");
        }
    }


    public void setTextShow(String text) {
        if (TextUtils.equals(text,"安装")){
            youxi_state.setBackgroundColor(Color.parseColor("#F6B756"));
        }else {
            youxi_state.setBackgroundColor(Color.parseColor("#4BB3FF"));
        }
        youxi_state.setText(text);
    }

    public void refishState(APKDownLoadEntity youXiEntity) {
        if (TextUtils.equals(youXiEntity.getDownLoadState(),APKDownLoadManager.State.downloading)){
            LUtils.e("下载中---接收"+youXiEntity.getPrross());
            LUtils.e(youxi_state);
            setTextShow(text_down_loading+youXiEntity.getPrross()+"%");
            if (youXiEntity.getPrross()==100){
                setTextShow(text_anzhuang);
            }
        }else  if (TextUtils.equals(youXiEntity.getDownLoadState(),APKDownLoadManager.State.stop)
                ||TextUtils.equals(youXiEntity.getDownLoadState(),APKDownLoadManager.State.ok)){
            File file=new File(youXiEntity.getFilePath());
            if (file.exists()&&file.length()==youXiEntity.getFileSize()&& PackageUtil.computeMD5(file).toUpperCase().equals(youXiEntity.getFileMd5().toUpperCase())){
                setTextShow(text_anzhuang);
                AppUtils.anZhuangAPk(context,youXiEntity.getFilePath());
            }else {
                setTextShow(text_down);
            }
        }else if (TextUtils.equals(youXiEntity.getDownLoadState(),APKDownLoadManager.State.generateing)){
            setTextShow(text_generateing);
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEvent(MessageEvent messageEvent) {
//        if (messageEvent.getCode()== EventCode.code_state_chanage&&messageEvent.getData() instanceof APKDownLoadEntity&& ((APKDownLoadEntity) messageEvent.getData()).getAppid()==viewData.getAppId()){
//            APKDownLoadEntity youXiEntity=((APKDownLoadEntity) messageEvent.getData());
//            if (TextUtils.equals(youXiEntity.getDownLoadState(),APKDownLoadManager.State.downloading)){
//                LUtils.e("下载中---接收"+youXiEntity.getPrross());
//                LUtils.e(youxi_state);
//                setTextShow(text_down_loading+youXiEntity.getPrross()+"%");
//                if (youXiEntity.getPrross()==100){
//                    setTextShow(text_anzhuang);
//                }
//            }else  if (TextUtils.equals(youXiEntity.getDownLoadState(),APKDownLoadManager.State.stop)
//                    ||TextUtils.equals(youXiEntity.getDownLoadState(),APKDownLoadManager.State.ok)){
//                File file=new File(youXiEntity.getFilePath());
//                if (file.exists()&&file.length()==youXiEntity.getFileSize()&& PackageUtil.computeMD5(file).toUpperCase().equals(youXiEntity.getFileMd5().toUpperCase())){
//                    setTextShow(text_anzhuang);
//                    AppUtils.anZhuangAPk(context,youXiEntity.getFilePath());
//                }else {
//                    setTextShow(text_down);
//                }
//            }else if (TextUtils.equals(youXiEntity.getDownLoadState(),APKDownLoadManager.State.generateing)){
//                setTextShow(text_generateing);
//            }
//        }
//    }
}

